package com.abgame.test.redis.controller;

import com.abgame.test.redis.utils.RedisUtils;
import com.abgame.test.redis.utils.lock.RedissonLockUtils;
import com.alibaba.fastjson.JSON;
import org.redisson.RedissonLockEntry;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author abgame
 * @date 2020/8/12 17:05
 */
@RequestMapping("/redis")
@RestController
public class RedisController {
    @Autowired
    RedisUtils redisUtils;

    private static final String TEST_KEY = "_test_key";
    private static final String LOCKE_TEST_KEY = "locke_test_key";

    @GetMapping("/set")
    public String setTest(){
        redisUtils.set(TEST_KEY, new Date());
        return "set success";
    }

    @GetMapping("/get")
    public String getTest(){
        Object rst = redisUtils.get(TEST_KEY);
        if(rst == null){
            return "无数据";
        }
        return JSON.toJSONString(rst);
    }


    @GetMapping("/lock")
    public String lockeTest(){
        System.out.println("start get lock ");
        RLock rLock = RedissonLockUtils.getLock(TEST_KEY);
        if(rLock == null){
            return "get lock fail";
        }
        System.out.println(" success get lock ");
        System.out.println(" start lock ");
        rLock.lock();
        System.out.println("success lock");
        rLock.unlock();
        System.out.println("finish unlock");

        return "lock finish";
    }

    @GetMapping("/tryLock")
    public String tryLock(){
        System.out.println("start tryLock ");
        boolean lockFlag = RedissonLockUtils.tryLock(TEST_KEY);
        if(!lockFlag){
            System.out.println("fail tryLock");
            return "tryLock fail";
        }
        System.out.println("success lock");
        System.out.println("do something");

        RedissonLockUtils.unlock(TEST_KEY);

        return "lock finish";
    }

    @GetMapping("/unlock")
    public String unlock(){
        System.out.println("start get lock ");
        RLock rLock = RedissonLockUtils.getLock(TEST_KEY);
        if(rLock == null){
            return "get lock fail";
        }
        System.out.println("success get lock");
        System.out.println("start unlock");
        rLock.unlock();
        System.out.println("success unlock");

        return "lock finish";
    }

    public String test(){

        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        threadLocal.set("sfsdfdsfds");
        String rst = threadLocal.get();
        return rst;
    }
}
